/*
 * @Author: Wangtao
 * @Date: 2022-07-12 18:29:32
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-09-22 16:42:00
 */
import { RouteLocationNormalized, NavigationGuardNext } from 'vue-router'
import router from './index'
import { PermissionModule } from '@/common/store/modules/permission'

import { userModule } from '@/common/store/modules/user'

import { resetRouter } from '@app/base/router'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false });

const WHITELIST = ['/login']

router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  // 路由权限 角色过滤
  NProgress.start()
  const PERMISSIONMODULE = PermissionModule()
  const USERMODULE = userModule()
  // 系统切换逻辑
  console.log(to)
  await USERMODULE.handleSwitchClientType(to.query)

  // 系统获取缓存
  await USERMODULE.getLoginCache()
  if (USERMODULE.loginToken && USERMODULE.sessionId) {
    if (to.path === '/login') {
      next()
    } else {
      if (!USERMODULE.loginState) {
        // 是否过用户信息
        console.log('getLoginInfoooooooooooooo')
        await USERMODULE.getLoginInfo()
      }
      console.log(PERMISSIONMODULE.isFilterRoute, 'PERMISSIONMODULE.isFilterRoute')
      if (PERMISSIONMODULE.isFilterRoute) {
        // 是否进行过角色权限过滤
        next()
      } else {
        // 过滤权限
        resetRouter()
        await USERMODULE.filterRole()
        PERMISSIONMODULE.dynamicRoutes.forEach((route: any) => {
          router.addRoute(route)
        })
        PERMISSIONMODULE.updateFilterState(true)
        next({ ...to, replace: true })
      }
    }
  } else {
    if (WHITELIST.indexOf(to.path) !== -1) {
      if (to.path === '/login') {
        USERMODULE.getPlatformInfo()
        next()
      } else {
        next()
      }
    } else {
      next(`/login`)
    }
  }
})

router.afterEach((to: any) => {
  NProgress.done()
  console.log(to, 'router-after')
})
